package tcp_udp;

import org.graylog2.syslog4j.Syslog;
import org.graylog2.syslog4j.SyslogConstants;
import org.graylog2.syslog4j.SyslogIF;

/**
 * Author: hu
 * Date: 2023/4/7 14:26
 */
public class ClientClass implements Runnable{

    // 用来记录发送数量
    public static int num = 0;
    private static ClientClass ClientClass = null;
    // 记录开始时间
    private static Long starttime = null;
    private static SyslogIF syslogIF;
    //控制循环结束的
    private boolean flag = true;
    private String host;
    private int port;



    private ClientClass (String host, int port) {
        this.host = host;
        this.port = port;
    }

    private ClientClass(){

    }

    public static long getspeed(){
        if(starttime == null){
            return 0L;
        }
        long endtime = System.currentTimeMillis();
        if((endtime-starttime)/1000==0){
            return 0L;
        }
        long speed = num / ((endtime-starttime)/1000);
        return speed;
    }

    public static synchronized ClientClass getClient(String host, int port)
    {
        if(ClientClass == null) {
            ClientClass = new ClientClass(host, port);
        }
        return ClientClass ;
    }

    public static void main(String[] args) {
        ClientClass cl = getClient("146.56.196.204" ,514);
        cl.run();
        cl.run();
        cl.run();
    }

    @Override
    public void run() {
        starttime = System.currentTimeMillis();
        try {
            //初始化标识位
            flag = true;
            //获取syslog的操作类，使用udp协议。syslog支持"udp", "tcp", "unix_syslog", "unix_socket"协议
            SyslogIF syslog = Syslog.getInstance("udp");
            //设置syslog服务器端地址   地址为之前你服务器的地址
            syslog.getConfig().setHost(host);
            //设置syslog接收端口，默认514
            syslog.getConfig().setPort(port);
            //拼接syslog日志
            syslog.log(SyslogConstants.LEVEL_INFO,"dbmgr hello udp");
//            while(flag) {
//                // 等级为debug
//                // 这句话就是发送数据
//                String str = "dbmgr [" + num + "]->" + "operator Protocol "+ Thread.currentThread().getName();
//                syslog.log(SyslogConstants.LEVEL_DEBUG, URLDecoder.decode(str,"utf-8"));
//                num++;
//                // 给程序缓冲时间，没有缓冲时间接受不到数据
//                Thread.sleep(100);
//            }
            //System.out.println(Thread.currentThread().getName()+" end");
        } catch (Exception e) {
            System.err.println("出错了");
            e.printStackTrace();
        }
    }

    public void shutdown() {
        try {
            //线程停止
            Thread.sleep(2000);
            //改变标识位
            flag = false;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
